import {GetQtController, MyWriteLog} from "./QtUtils";
import {CODE_ERROR_APP_WEBSOCKET} from "./QtBaseController";

export default class QtWebSocketUtils
{
    constructor(strRemoteRenderIp,remotePort,fnConnectCallback)
    {
        this.isConnected = false;
        this.webAppSocket = null;
        this.strRemoteRenderIp = strRemoteRenderIp;
        this.remotePort = remotePort;
        this.fnConnectCallback = fnConnectCallback;
        this.fnReConnectedCallback = null;
        this.isReconneccted = false;

        this.initDataManager();
    }

    setReConnectedCallback(fncallback) {
        this.fnReConnectedCallback = fncallback;
    }

    initDataManager()
    {
		this.startAppSocket();
    }

	startAppSocket()
    {
        let preHost = 'ws://';
        if(GetQtController().inParam.dataUrl.indexOf('https') != -1) {
          preHost = 'wss://';
        }
        console.log('websocketUtils',preHost + this.strRemoteRenderIp + ':'+String(this.remotePort)+'/');
        this.webAppSocket = new WebSocket(preHost + this.strRemoteRenderIp + ':'+String(this.remotePort)+'/');
        if(!this.webAppSocket)
        {
            this.showDisconnectMessage();
            return;
        }

        this.webAppSocket.binaryType = 'arraybuffer';
        this.webAppSocket.onopen = this.onAppSocketOpen.bind(this);
        this.webAppSocket.onmessage = this.onAppData.bind(this);
        this.webAppSocket.onerror = this.onError.bind(this);
        this.webAppSocket.onclose = this.onClose.bind(this);
        window.addEventListener("beforeunload", function (e) {
          if(this.webAppSocket) {
            this.webAppSocket.close();
          }
        });

    }

    startReConnectTimer() {
        // this.isReconneccted = true;
        // setTimeout(() => {
        //     this.startAppSocket();
        // }, 2000);
    }

    onClose(event) {
        console.log('onClose',event);
        this.isConnected = false;
        this.startReConnectTimer();
        GetQtController().onInitError(CODE_ERROR_APP_WEBSOCKET, 'App 业务WebSocket 连接失败')
    }

    onError(event) {
        console.log('onError',event);
        this.isConnected = false;
        if(this.fnConnectCallback) {
            this.fnConnectCallback(false,event);
            this.fnConnectCallback = null;
        }
    }

    startAppSession()
    {
        if(this.webAppSocket)
        {
            if(this.webAppSocket.readyState === WebSocket.OPEN)
            {
                this.isConnected = true;
                this.removeDisconnectMessage();

            }
            else
            {
                this.showDisconnectMessage();
                console.log("try 'startCmdSession' but socket is not connected yet");
            }

            if(this.fnConnectCallback) {
                this.fnConnectCallback(this.isConnected);
                this.fnConnectCallback = null;
            }
            if(this.isConnected && this.isReconneccted && this.fnReConnectedCallback) {
                this.fnReConnectedCallback();
            }
        }
    }

    onAppSocketOpen()
    {
        setTimeout(this.startAppSession.bind(this),1500);
        console.log('websocketUtils','onAppSocketOpen--' + this.strRemoteRenderIp + ':'+String(this.remotePort));
    }

    onAppData(event)
    {
      // let strData = event.data;
      // // console.log('onAppData--args',strData);
      // if(!(typeof(strData)=='string')) {
      //   //不是String则返回
      //   return;
      // }
      // let index = strData.indexOf('(');
      // let nextIndex = strData.indexOf(')');
      //
      // if(index>=0 && nextIndex>=0)
      // {
      //   let strCode = strData.slice(0,index);
      //   let strParams = strData.slice(index+1,nextIndex);
      //   strParams = strParams.replace(/'/g,'"')
      //   //转成json格式字符串
      //   strParams = '[' + strParams;
      //   strParams = strParams + ']';
      //   strParams = strParams.replace("，",",");
      //   strParams = strParams.replace(", ",",");
      //   strParams = strParams.replace("， ",",")
      //   let jsonArray = JSON.parse(strParams);
      //   let args = [];
      //   for(let i in jsonArray) {
      //       if(jsonArray[i] instanceof Object) {
      //           let str = JSON.stringify(jsonArray[i]);
      //           args.push(str);
      //       }else {
      //         args.push(jsonArray[i]);
      //       }
      //   }
      //   if (GetQtController().GetInParam().isShowLog && strCode.indexOf("VS_UpdateMapPosition") == -1) {
      //     console.log('onAppData--args',args);
      //   }
      //   PubSub.publish(strCode,args);
      // }

      let strData = event.data;
      if(GetQtController().GetInParam().isLog) {
        console.log(strData);
      }
      if(!(typeof(strData)=='string')) {
        //不是String则返回
        return;
      }
      try {
          eval(strData);
      }catch (e) {
          console.log('eval报错',e);
      }
	}

    removeDisconnectMessage()
    {
        // if(this.messageField)
        // {
        //     this.messageField.remove;
        //     this.messageField = null;
        // }
    }

    sendAppText(text)
    {
        if(this.isConnected)
        {
            this.webAppSocket.binaryType = 'blob';
            this.webAppSocket.send(text);
        }
    }
    // ________________________________________________

  close() {
      if(this.webAppSocket) {
        this.webAppSocket.close();
      }
  }
}
